package com.yym.project.dao.impl;

import com.yym.project.dao.IBookDao;
import com.yym.project.entity.Book;
import com.yym.project.utils.Dbutil;
import com.yym.project.utils.RowMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class IBookDaoImpl implements IBookDao {

    @Override
    public int save(Book book) throws Exception {
        //获得连接对象
        Connection connection = Dbutil.getConnection();
        String sql = "insert into tb_books (bookName,author,price,publish) values(?,?,?,?)";
        int row = Dbutil.executeUpdate(connection,sql,book.getBookName(),book.getAuthor(),book.getPrice(),book.getPublish());
        Dbutil.close(connection);
        return row;
    }

    @Override
    public int update(Book book) throws Exception {

        return 0;

    }

    @Override
    public int delete(Integer id) throws Exception {
        Connection connection = Dbutil.getConnection();
        String sql = "delete from tb_books where id=?";
        int row =Dbutil.executeUpdate(connection,sql,id);
        Dbutil.close(connection);
        return row;
    }

    @Override
    public Book selectByName(String name) throws Exception {
        // 连接对象
        Connection conn = Dbutil.getConnection();
        String sql = "select * from tb_books where bookname=?";
        return Dbutil.query(conn, sql, new RowMapper<Book>() {
            @Override
            public Book mappperTo(ResultSet rs) throws Exception {
                Book book = null;
                if(rs.next()){
                    book = new Book();
                    book.setId( rs.getInt("id") );
                    book.setBookName(rs.getString("bookName"));
                    book.setPrice( rs.getDouble("price") );
                    book.setAuthor(rs.getString("author"));
                    book.setPublish(rs.getDate("publish"));
                }
                return book;
            }
        }, name);
    }

    @Override
    public List<Book> list() throws Exception {
        Connection conn = Dbutil.getConnection();
        String sql = "select * from tb_books";
        return Dbutil.query(conn, sql, new RowMapper< ArrayList<Book>  >() {
            @Override
            public ArrayList<Book> mappperTo(ResultSet rs) throws Exception {
                ArrayList<Book> list = new ArrayList<>();
                while (rs.next()){
                    Book book = new Book();
                    book.setId( rs.getInt("id") );
                    book.setBookName(rs.getString("bookName"));
                    book.setPrice( rs.getDouble("price") );
                    book.setAuthor(rs.getString("author"));
                    book.setPublish(rs.getDate("publish"));
                    list.add(book);
                }
                return list;
            }
        });

    }

}
